package com.cmii.sjw.department.control.common;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class AccessTokenFetcher {
    private static final String AUTH_URL = "http://23.210.23.13:9000/auth/realms/edubigdata/protocol/openid-connect/token";
    private static final String CLIENT_ID = "a82be5f8-f9ec-4f98-8fb0-6f10e38e4616";
    private static final String CLIENT_SECRET = "772ce556-32f7-4614-bb33-d1d1b38dacf9";
    private static final String GRANT_TYPE = "client_credentials";

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    private static long expirationTime;

    public String fetchAccessToken() {
        long currentTime = System.currentTimeMillis();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("client_id", CLIENT_ID);
        body.add("client_secret", CLIENT_SECRET);
        body.add("grant_type", GRANT_TYPE);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(AUTH_URL, request, String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();
            try {
                JsonNode jsonNode = objectMapper.readTree(responseBody);
                String accessToken = jsonNode.path("access_token").asText();
                int expiresIn = jsonNode.path("expires_in").asInt();
                expirationTime = currentTime + (expiresIn * 1000L); // 设置过期时间
                log.info("获取到的访问token: {}", accessToken);
                return accessToken;
            } catch (Exception e) {
                log.error("访问token失败: {}", e.getMessage(), e);
                throw new RuntimeException("访问token失败", e);
            }
        } else {
            log.error("获取访问令牌失败: {}", response.getStatusCodeValue());
            throw new RuntimeException("获取token失败");
        }
    }
}
